﻿using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using Microsoft.Web.Preview.Services;
using Lx.Web.Common.UI;
using Lx.Web.Common.ControlsUI;
using Model;

namespace WebServices.User
{
    /// <summary>
    /// Learn 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://www.italki.com/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.Web.Script.Services.ScriptService]
    public class Contacts : System.Web.Services.WebService
    {
        /// <summary>
        /// 搜索会员（0：会员列表UserSummaryInfoModel List、1：搜索数量int）
        /// </summary>
        /// <param name="learnL">学习语言</param>
        /// <param name="speakL">母语</param>
        /// <param name="nation">来自国家</param>
        /// <param name="maxAge">最大年龄</param>
        /// <param name="minAge">最小年龄</param>
        /// <param name="gender">性别（0女、1男、空默认）</param>
        /// <param name="city">当前所在城市</param>
        /// <param name="isAvatar">是否只显示有头像会员（1显示只有头像的会员，0默认）</param>
        /// <param name="isChatNow">是否只显示能聊天的会员</param>
        /// <param name="pageIndex">页索引</param>
        /// <param name="pageSize">页大小</param>
        /// <param name="memberno">当前会员号</param>
        [WebMethod]
        public ArrayList GetMembers(string learnL, string speakL, string nation, string maxAge, string minAge, string gender, string city, bool isAvatar, bool isChatNow, string memberno, int pageIndex, int pageSize)
        {
            return BLF.WWW_WWW.Contact.Contacts.GetMembers(learnL, speakL, nation, maxAge, minAge, gender, city, isAvatar, isChatNow, pageIndex, pageSize, memberno);
        }
        /// <summary>
        /// 搜索会员（0：会员列表UserSummaryInfoModel List、1：搜索数量int）
        /// </summary>
        /// <param name="nnMnMe">昵称名或会员email或会员号</param>
        /// <param name="pageIndex">页索引</param>
        /// <param name="pageSize">页大小</param>
        /// <param name="memberno">当前会员号</param>
        /// <returns>0：会员列表UserSummaryInfoModel List、1：搜索数量int</returns>
        [WebMethod]
        public ArrayList GetSMembers(string nnMnMe, string memberno, int pageIndex, int pageSize)
        {
            return BLF.WWW_WWW.Contact.Contacts.GetSMembers(nnMnMe, memberno, pageIndex, pageSize);
        }
        /// <summary>
        /// 根据当前会员号获取会员相关信息
        /// </summary>
        /// <param name="memberno">当前会员号</param>
        /// <param name="memberType">获取会员类型（0结交新朋友信息，1我的好友信息，2我收到请求的会员信息，3我发送请求的会员信息）</param>
        /// <param name="pageIndex">pageIndex</param>
        /// <param name="pageSize">pageSize</param>
        /// <param name="recordCount">输出记录</param>
        /// <returns>会员列表</returns>
        [WebMethod]
        public ArrayList GetContactMembers(string memberno, int memberType, int pageIndex, int pageSize)
        {
            return BLF.WWW_WWW.Contact.Contacts.GetContactMembers(memberno, memberType, pageIndex, pageSize);
        }
        /// <summary>
        /// 删除联系人
        /// </summary>
        ///<param name="myMemberno">我的会员号</param>
        /// <param name="fMemberno">朋友的会员号</param>
        /// <returns>CommonMessage</returns>
        [WebMethod]
        public CommonMessage DeleContacts(string myMemberno, string fMemberno)
        {
            if (HttpContext.Current.User.Identity.Name == "")
            {
                return new CommonMessage();
            }
            return BLF.WWW_WWW.Contact.Contacts.DeleContacts(myMemberno, fMemberno);
        }
        /// <summary>
        /// 同意添加朋友
        /// </summary>
        ///<param name="myMemberno">我的会员号</param>
        /// <param name="fMemberno">朋友的会员号</param>
        /// <returns>CommonMessage</returns>
        [WebMethod]
        public CommonMessage AcceptFriend(string myMemberno, string fMemberno)
        {
            if (HttpContext.Current.User.Identity.Name == "")
            {
                return new CommonMessage();
            }
            return BLF.WWW_WWW.Contact.Contacts.AcceptFriend(myMemberno, fMemberno);
        }
        /// <summary>
        /// 添加新朋友Effect 1:添加成功, 0:好友数量超限, 2:已经是联系人
        /// </summary>        
        /// <param name="myMemberno">我的会员号</param>
        /// <param name="fMemberno">添加的会员号</param>
        /// <returns>CommonMessage Effect 1:添加成功, 0:好友数量超限, 2:已经是联系人</returns>
        [WebMethod]
        public CommonMessage AddNewFriend(string myMemberno, string fMemberno)
        {
            if (HttpContext.Current.User.Identity.Name == "")
            {
                return new CommonMessage();
            }
            return BLF.WWW_WWW.Contact.Contacts.AddNewFriend(myMemberno, fMemberno);
        }
        /// <summary>
        /// 邀请好友（发送邮件）
        /// </summary>
        /// <param name="NamesMails">好友名字、email(名字与email以‘,’格开，多条以‘/’格开)</param>
        /// <param name="title">标题</param>
        /// <param name="body">内容</param>
        /// <param name="eSubject">italki会员信件标题</param>
        /// <param name="eBody">italki会员信件内容</param>
        /// <param name="rSubject">非italki会员信件标题</param>
        /// <param name="rBody">非italki会员信件内容</param>
        /// <returns></returns>
        [WebMethod]
        public CommonMessage InviteFriends(string NamesMails, string title, string body)
        {
            CommonMessage comMes = new CommonMessage();
            comMes.Msg = "";
            string memberno = HttpContext.Current.User.Identity.Name;
            if (memberno == "")
            {
                return comMes;
            }
            string[] namemail = NamesMails.Split('/');
            int nmLength = namemail.Length-1;
            if (nmLength != 0)
            {
                BaseControl baseControl = new BaseControl();
                string eSubject = Globals.ReadTextByXmlNode(baseControl.FormatFileName(Server.MapPath(String.Format("/Template/emailxml/{0}/InvitationSend.xml", Globals.Language))), "email", "subject", "");
                string eBody = Globals.ReadTextByXmlNode(baseControl.FormatFileName(Server.MapPath(String.Format("/Template/emailxml/{0}/InvitationSend.xml", Globals.Language))), "email", "body", "");
                string rSubject = Globals.ReadTextByXmlNode(baseControl.FormatFileName(Server.MapPath(String.Format("/Template/emailxml/{0}/InvitationRegister.xml", Globals.Language))), "email", "subject", "");
                string rBody = Globals.ReadTextByXmlNode(baseControl.FormatFileName(Server.MapPath(String.Format("/Template/emailxml/{0}/InvitationRegister.xml", Globals.Language))), "email", "body", "");
                ArrayList outList = new ArrayList();
                for (int i = 0; i < nmLength; i++)
                {
                    string[] nmSplit = namemail[i].Split(',');
                    if (!System.Text.RegularExpressions.Regex.IsMatch(nmSplit[1], "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"))
                    {
                        return comMes;
                    }
                    CommonMessage mes = BLF.WWW_WWW.Contact.Contacts.InviteFriend(memberno, nmSplit[1], out outList);
                    string mNickName = (string)outList[0];
                    switch (mes.Effect)
                    {
                        case 1:
                            Model.WWW_User.User.UserNotifiModel fInfo = outList[1] as Model.WWW_User.User.UserNotifiModel;
                            if ((1 & fInfo.EmailOption) == 1)
                            {
                                MsMailSend.SendMail(eSubject.Replace("{0}", mNickName), eBody.Replace("{0}", mNickName).Replace("{1}", fInfo.Nickname).Replace("{2}", memberno).Replace("{3}", fInfo.MemberNo).Replace("{4}", title).Replace("{5}", body), nmSplit[1], null, true);
                            }
                            comMes.Msg += "!" + nmSplit[0]+"|";
                            comMes.State = true;
                            break;
                        case 0:
                            MsMailSend.SendMail(rSubject.Replace("$$Email$$", nmSplit[1]).Replace("$$NickName$$", mNickName).Replace("$$MemberNo$$", memberno).Replace("$$FriendName$$", nmSplit[0]), rBody.Replace("$$Email$$", nmSplit[1]).Replace("$$NickName$$", mNickName).Replace("$$MemberNo$$", memberno).Replace("$$FriendName$$", nmSplit[0]).Replace("$$Message$$", body), nmSplit[1], null, true);
                            comMes.Msg += "!" + nmSplit[0]+"|";
                            comMes.State = true;
                            break;
                        case 10:
                            comMes.Msg += "~" + nmSplit[0]+"|";
                            comMes.State = true;
                            break;
                    }                    
                }
            }
            return comMes;
        }
        /// <summary>
        /// 发送邮件(InvitationSend.xml)
        /// </summary>
        /// <param name="fMemberno">添加好友的会员号</param>
        /// <param name="fNickName">添加好友的昵称名</param>
        /// <param name="myNickName">当前会员的昵称名</param>
        /// <param name="eMail">添加好友的email</param>
        /// <param name="msg">消息</param>
        /// <returns></returns>
        [WebMethod]
        public CommonMessage SendMail1(string fMemberno, string fNickName, string myNickName, string eMail, string msg)
        {
            CommonMessage comMes = new CommonMessage();
            comMes.Msg = "";
            string myMemberno = HttpContext.Current.User.Identity.Name;
            if (myMemberno == "" || fMemberno == "")
            {
                return comMes;
            }
            if (!System.Text.RegularExpressions.Regex.IsMatch(eMail, "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"))
            {
                return comMes;
            }
            else
            {
                BaseControl baseControl = new BaseControl();
                string eSubject = Globals.ReadTextByXmlNode(baseControl.FormatFileName(Server.MapPath(String.Format("/Template/emailxml/{0}/InvitationSend.xml", Globals.Language)), Globals.Language), "email", "subject", "");
                string eBody = Globals.ReadTextByXmlNode(baseControl.FormatFileName(Server.MapPath(String.Format("/Template/emailxml/{0}/InvitationSend.xml", Globals.Language)), Globals.Language), "email", "body", "");
                new System.Threading.Thread(new System.Threading.ThreadStart(delegate
                {
                    eSubject = eSubject.Replace("{0}", myNickName);
                    eBody = eBody.Replace("{0}", myNickName).Replace("{1}", fNickName).Replace("{2}", myMemberno).Replace("{3}", fMemberno).Replace("{4}", msg);
                    MsMailSend.SendMail(eSubject, eBody, eMail, null, true);
                })).Start();
                comMes.State = true;
            }
            return comMes;
        }
        /// <summary>
        /// 获取会员好友列表(Nickname,MemberNo,Avatar)(Share)
        /// </summary>
        /// <param name="memberno">当前会员号</param>
        /// <param name="pageIndex">pageIndex</param>
        /// <param name="pageSize">pageSize</param>        
        /// <returns>ArrayList（0好友列表 1PageableObject）</returns>
        [WebMethod]
        public ArrayList GetMemberFriends(string memberno, int pageIndex, int pageSize)
        {
            return BLF.WWW_WWW.Contact.Contacts.GetMemberFriends(memberno, pageIndex, pageSize);
        }
        /// <summary>
        /// 发送邮件(Shareo.xml)
        /// </summary>
        /// <param name="fromName">发送者昵称名</param>
        /// <param name="fEmails">被发送者email</param>
        /// <param name="shareContent">共享内容</param>
        /// <param name="SharedURL">共享url</param>
        /// <returns>CommonMessage</returns>
        [WebMethod]
        public CommonMessage SendMail(string fromName,string fEmails, string SharedURL)
        {
            CommonMessage comMes = new CommonMessage();            
            string myMemberno = HttpContext.Current.User.Identity.Name;
            if (myMemberno == "" || SharedURL == "")
            {
                return comMes;
            }
            string shareContent = "";
            int type = 0;
            string numberno = "";
            SharedURL = SharedURL.ToLower();
            string subLink = "link";
            if (SharedURL.StartsWith(System.Configuration.ConfigurationManager.AppSettings["WWWHost"].TrimEnd('/').ToLower() + "/answers/question/"))
            {
                string[] quesArr = SharedURL.Split('/');
                string question = quesArr[quesArr.Length - 1];
                string[] strArr = question.Split('-');
                if (strArr.Length == 1)
                {
                    numberno = strArr[0].Split('.')[0];
                }
                else
                {
                    numberno = strArr[0];                    
                }
                SharedURL = System.Configuration.ConfigurationManager.AppSettings["WWWHost"].TrimEnd('/').ToLower() + "/answers/question/" + numberno + ".htm";//移除ID后参数
                //int index = SharedURL.IndexOf("QuesID=");
                //numberno = SharedURL.Substring(index + "QuesID=".Length);
                type = 1;
                subLink = "question";

            }
            if (type == 1)
                shareContent = BLF.WWW_WWW.Contact.Contacts.Title(type, numberno);
            BaseControl baseControl = new BaseControl();
            string eSubject = Globals.ReadTextByXmlNode(baseControl.FormatFileName(Server.MapPath(String.Format("/Template/emailxml/{0}/Shareo.xml", Globals.Language))), "email", "subject", "");
            string eBody = Globals.ReadTextByXmlNode(baseControl.FormatFileName(Server.MapPath(String.Format("/Template/emailxml/{0}/Shareo.xml", Globals.Language))), "email", "body", "");            
            string[] emails = fEmails.Split(',');
            new System.Threading.Thread(new System.Threading.ThreadStart(delegate
            {
                for (int i = 0; i < emails.Length; i++)
                {
                    if (System.Text.RegularExpressions.Regex.IsMatch(emails[i], "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"))
                    {
                        eSubject = eSubject.Replace("{0}", fromName).Replace("{2}", subLink);
                        eBody = eBody.Replace("{0}", fromName).Replace("{1}", SharedURL).Replace("{2}", shareContent == "" ? SharedURL : shareContent).Replace("{3}", subLink);
                        MsMailSend.SendMail(eSubject, eBody, emails[i], null, true);                        
                    }
                }
            })).Start();
            return comMes;
        }
        /// <summary>
        /// 发送邮件(Sharei.xml)
        /// </summary>
        /// <param name="fromName">发送者昵称名</param>
        /// <param name="friendsMn">被发送者email列表</param>
        /// <param name="msg">信息</param>
        /// <param name="SharedURL">共享url</param>
        /// <returns>CommonMessage</returns>
        [WebMethod]
        public CommonMessage SendItalkiMail(string fromName, ArrayList friendsMn, string SharedURL)
        {
            CommonMessage comMes = new CommonMessage();
            string myMemberno = HttpContext.Current.User.Identity.Name;
            if (myMemberno == "")
            {
                return comMes;
            }
            string shareContent = "";
            int type = 0;
            string numberno = "";
            SharedURL = SharedURL.ToLower();
            string subLink = "link";
            if (SharedURL.StartsWith(System.Configuration.ConfigurationManager.AppSettings["WWWHost"].TrimEnd('/').ToLower() + "/answers/question/"))
            {
                string[] quesArr = SharedURL.Split('/');
                string question = quesArr[quesArr.Length - 1];
                string[] strArr = question.Split('-');
                if (strArr.Length == 2)
                {
                    numberno = strArr[0].Split('.')[0];
                }
                else
                {
                    numberno = strArr[0];
                }
                SharedURL = System.Configuration.ConfigurationManager.AppSettings["WWWHost"].TrimEnd('/').ToLower() + "/answers/question/" + numberno + ".htm";//移除ID后参数
                type = 1;
                subLink = "question";

            }
            if(type == 1)
                shareContent = BLF.WWW_WWW.Contact.Contacts.Title(type, numberno);
            BaseControl baseControl = new BaseControl();
            string eSubject = Globals.ReadTextByXmlNode(baseControl.FormatFileName(Server.MapPath(String.Format("/Template/emailxml/{0}/Sharei.xml", Globals.Language))), "email", "subject", "");
            string eBody = Globals.ReadTextByXmlNode(baseControl.FormatFileName(Server.MapPath(String.Format("/Template/emailxml/{0}/Sharei.xml", Globals.Language))), "email", "body", "");
            for (int i = 0; i < friendsMn.Count; i++)
            {
                if ((string)friendsMn[i] != "")
                {
                    eSubject = eSubject.Replace("{0}", fromName).Replace("{2}", subLink);
                    eBody = eBody.Replace("{0}", fromName).Replace("{1}", SharedURL).Replace("{2}", shareContent == "" ? SharedURL : shareContent).Replace("{3}", subLink).Replace("{4}", myMemberno);
                    BLF.WWW_User.UserMail.Mail.WriteInform((string)friendsMn[i], myMemberno, eSubject, eBody);
                }
            }            
            return comMes;
        }
    }
}
